﻿#include "datamanager.h"
#include "databasemanager.h"

#include "model/deviceinstancemanager.h"
#include "3rdparty/includes/device/idevice.h"

#include <QDebug>
#include <QFile>
#include <QCoreApplication>
#include <QDirIterator>
#include <QStandardPaths>

static DataManager *g_instance = nullptr;
DataManager *DataManager::instance()
{
    if (!g_instance) {
        g_instance = new DataManager();
    }
    return g_instance;
}

DataManager::DataManager(QObject *parent)
    : QObject(parent)
{
    QString dataPath = QStandardPaths::writableLocation(QStandardPaths::AppConfigLocation) + "/datas";
    if (!QDir().mkpath(dataPath)) {
        qWarning() << "not creator data path: " << dataPath;
        return;
    }
    m_dbManager = new DatabaseManager(QDir(dataPath).filePath("emsdata.db"));
}

void DataManager::initialize()
{
    m_parameterTableOverviews = m_dbManager->loadParameterTableOverviews();
    loadAndCacheDeviceModel();
    m_hardwareTemplateOverviews = m_dbManager->loadHardwareTemplateOverviews();
    m_testTemplateOverviews = m_dbManager->loadTestTemplateOverviews();
}

void DataManager::selectTestTemplate(int id)
{
    if (id <= 0) {
        if (m_selectedTestTemplate)
            m_selectedTestTemplate.clear();
        return;
    }

    TestTemplatePtr tt = m_dbManager->loadFullTestTemplate(id);
    if (!tt) {
        qWarning() << "Failed to load Test Template with ID:" << id;
        if (m_selectedHardwareTemplate)
            m_selectedHardwareTemplate.clear();
        return;
    }

    m_selectedTestTemplate = tt;
    qDebug() << "Test template" << id << "(\"" << tt->name << "\") is selected and fully loaded.";
}

void DataManager::selectHardwareTemplate(int id)
{
    //  处理清空选择的情况
    if (id <= 0) {
        if (m_selectedHardwareTemplate)
            m_selectedHardwareTemplate.clear();
        return;
    }

    //  加载或从缓存获取硬件模板的“骨架”
    HardwareTemplatePtr hwTemplate = loadAndCacheHardwareTemplate(id);

    if (!hwTemplate) {
        qWarning() << "Failed to load or find Hardware Template with ID:" << id;
        if (m_selectedHardwareTemplate)
            m_selectedHardwareTemplate.clear();
        return;
    }

    //  将完全填充好的硬件模板设为“当前选中”
    m_selectedHardwareTemplate = hwTemplate;
    //  发射信号，通知UI更新
    qDebug() << "Hardware template" << id << "(\"" << hwTemplate->name << "\") is selected and fully loaded.";
}

/**
 * @brief 获取一个完整的、填充好的硬件模板，但不改变当前的选中状态。
 *
 * 这个函数会执行与 selectHardwareTemplate 类似的加载和绑定逻辑，
 * 但它不会修改 m_selectedHardwareTemplate 成员，也不会发射信号。
 * 主要用于UI批量加载等场景。
 *
 * @param id 要获取的硬件模板的ID。
 * @return HardwareTemplatePtr 指向完整硬件模板的智能指针，如果失败则返回nullptr。
 */
const HardwareTemplatePtr DataManager::getFullHardwareTemplate(int id)
{
    if (id <= 0)
        return nullptr;

    //加载或从缓存获取硬件模板的“骨架”
    HardwareTemplatePtr hwTemplate = loadAndCacheHardwareTemplate(id);
    if (!hwTemplate) {
        qWarning() << "Failed to get full HW Template (skeleton not found) for ID:" << id;
        return nullptr;
    }

    return hwTemplate;
}

const TestTemplatePtr DataManager::getFullTestTemplate(int id)
{
    if (id <= 0)
        return nullptr;

    //加载或从缓存获取硬件模板的“骨架”
    TestTemplatePtr testTemplate = loadAndCacheTestTemplate(id);
    if (!testTemplate) {
        qWarning() << "Failed to get full testTemplate (skeleton not found) for ID:" << id;
        return nullptr;
    }

    return testTemplate;
}

const QList<OverviewItem> &DataManager::getHardwareTemplateOverviews() const
{
    return m_hardwareTemplateOverviews;
}

const QList<OverviewItem> &DataManager::getParameterTableOverviews() const
{
    return m_parameterTableOverviews;
}
const QList<OverviewItem> &DataManager::getTestTemplateOverviews() const
{
    return m_testTemplateOverviews;
}

HardwareTemplatePtr DataManager::getSelectedHardwareTemplate() const
{
    return m_selectedHardwareTemplate;
}
TestTemplatePtr DataManager::getSelectedTestTemplate() const
{
    return m_selectedTestTemplate;
}

AttTableList DataManager::getAttTable(int tableId)
{
    return m_dbManager ? m_dbManager->loadAttTable(tableId) : AttTableList {};
}

TransducerTableList DataManager::getTransducerTable(int tableId)
{
    return m_dbManager ? m_dbManager->loadTransducerTable(tableId) : TransducerTableList {};
}

LimitLineList DataManager::getLimitLineTable(int tableId)
{
    return m_dbManager ? m_dbManager->loadLimitLineTable(tableId) : LimitLineList {};
}

QList<FreqTableConfig> DataManager::getFreqTable(int tableId)
{
    return m_dbManager ? m_dbManager->loadFreqTable(tableId) : QList<FreqTableConfig> {};
}

QList<CalTableConfig> DataManager::getCalibrationTable(int tableId)
{
    return m_dbManager ? m_dbManager->loadCalibrationTable(tableId) : QList<CalTableConfig> {};
}

TestTemplatePtr DataManager::addTestTemplate(const QString &name)
{
    //  在内存中构建一个包含默认子区间的完整对象
    TestTemplatePtr newTemplate = QSharedPointer<TestTemplate>::create();
    newTemplate->id = 0; // 明确是新的
    newTemplate->name = name;

    try {
        // 创建一个默认子区间（占位，可在 UI 中继续编辑）
        TestSubBandPtr sb = QSharedPointer<TestSubBand>::create();
        sb->id = 0;
        sb->hardwareTemplateID = 0; // 暂未绑定硬件模板
        sb->startFreq = 80e6;       // 80 MHz
        sb->stopFreq = 1000e6;      // 100 MHz
        sb->stepMode = AxisScale::Linear;
        sb->stepSize = 1e6;    //默认 LIN：1MHz
        sb->dwellTime = 100.0; // 100 ms
        sb->freqPlan = FrequencyPlanType::SweepLinear;
        sb->freqTableID = 0; // 暂不使用频表
        sb->immunityLevelType = ImmunityLevelType::Fixed;
        sb->immunityLevelTableID = 0;  // 暂不使用极值表
        sb->immunityLevelValue = 22.3; //  (22.3 Vm无设备测试空跑，正向功率计设置30dBm,反向 0，无其它参数时，干扰电平为22.3)
        sb->upperTolerance = 0.2;
        sb->lowerTolerance = 0;
        sb->generatorModulation = GeneratorModulationType::Off;
        sb->plumWidth = 500;   //us
        sb->plumPeriod = 1000; //us
        newTemplate->subBands.push_back(sb);
    } catch (const std::bad_alloc &e) {
        qWarning() << "Memory allocation failed while creating default sub-band for new test template:" << e.what();
        return nullptr;
    }

    //  调用 DatabaseManager 持久化（会回填模板ID与子区间ID）
    if (!m_dbManager || !m_dbManager->insertTestTemplate(*newTemplate)) {
        qWarning() << "Database failed to insert the new test template.";
        return nullptr;
    }

    //  更新内存状态 (缓存和概览列表)
    OverviewItem item;
    item.id = newTemplate->id;
    item.name = newTemplate->name;
    m_testTemplateOverviews.append(item);
    m_testTemplateCache.insert(newTemplate->id, newTemplate);

    emit sig_testTemplatesChanged();

    qDebug() << "Successfully created new test template. ID:" << newTemplate->id;
    return newTemplate;
}

bool DataManager::removeTestTemplate(int id)
{
    if (id <= 0) {
        qWarning() << "DataManager::removeTestTemplate: Invalid ID (" << id << ") provided.";
        return false;
    }

    //  调用数据库层执行删除操作
    // 假设它在失败时会打印详细的SQL错误。
    if (!m_dbManager->deleteTestTemplate(id)) {
        qWarning() << "Database operation failed for deleting test template" << id;
        return false;
    }

    //  从内存中的概览列表中移除
    qDebug() << "Searching for hardware template" << id << "in overview list to remove.";

    // 使用 std::remove_if 将要删除的元素移动到列表末尾
    auto newEnd = std::remove_if(m_testTemplateOverviews.begin(),
                                 m_testTemplateOverviews.end(),
                                 [id](const OverviewItem &item) {
                                     return item.id == id;
                                 });

    bool removedFromOverviews = (newEnd != m_testTemplateOverviews.end());

    // 使用 QList::erase 删除从 newEnd 到结尾的所有元素
    if (removedFromOverviews) {
        m_testTemplateOverviews.erase(newEnd, m_testTemplateOverviews.end());
        qDebug() << "Removed test template" << id << "from overview list.";
    }

    //  从缓存中移除
    if (m_testTemplateCache.contains(id)) {
        m_testTemplateCache.remove(id);
        qDebug() << "Removed test template" << id << "from cache.";
    }

    //  检查并清空当前选中状态
    //    bool selectionCleared = false;
    if (m_selectedTestTemplate && m_selectedTestTemplate->id == id) {
        m_selectedTestTemplate.clear(); // 清空智能指针
                                        //        selectionCleared = true;
        qDebug() << "Cleared the current selection as it was the deleted template.";
    }
    emit sig_testTemplatesChanged();

    qDebug() << "Successfully removed test template" << id;
    return true;
}

bool DataManager::updateTestTemplate(TestTemplatePtr testTemplate)
{
    if (!testTemplate || testTemplate->id <= 0) {
        qWarning() << "DataManager::updateTestTemplate: Invalid or non-existent template provided for update.";
        return false;
    }

    int commonType = -1;
    for (const auto &sbp : testTemplate->subBands) {
        if (!sbp)
            continue;
        const int hwId = sbp->hardwareTemplateID;
        if (hwId <= 0) {
            qWarning() << "Invalid hardware template id:" << hwId;
            return false;
        }
        const int t = m_dbManager->getHardwareTemplateType(hwId);
        if (t < 0) {
            qWarning() << "Invalid hardware template type:" << t;
            return false;
        }
        if (commonType == -1)
            commonType = t;
        else if (t != commonType) {
            qWarning() << "Hardware template types mismatch in subbands";
            return false;
        }
    }
    testTemplate->flowKind = static_cast<HardwareTemplateType>(commonType);
    qDebug() << "Attempting to update testTemplate template with ID:" << testTemplate->id;

    const auto &overviews = getTestTemplateOverviews();
    for (const auto &item : overviews) {
        // 如果找到另一个ID不同但名称相同的模板
        if (item.id != testTemplate->id && item.name.compare(testTemplate->name, Qt::CaseInsensitive) == 0) {
            qWarning() << " Failed. Another template with the name '" << testTemplate->name << "' already exists.";
            return false;
        }
    }

    for (const auto &sbp : testTemplate->subBands) {
        if (!sbp)
            continue;
        if (sbp->hardwareTemplateID <= 0) {
            qWarning() << "SubBand has no hardwareTemplateID, skip/abort";
            return false;
        }
    }

    //  委托给DatabaseManager执行持久化
    // 通过“先删除旧设备，再插入新设备”的策略来同步数据。
    if (!m_dbManager->updateTestTemplate(*testTemplate)) { // 解引用传递
        qWarning() << "Database operation failed for updating testTemplate template" << testTemplate->id;
        return false;
    }

    // 用包含了最新数据的智能指针，替换掉缓存中旧的那个
    m_testTemplateCache.insert(testTemplate->id, testTemplate);
    qDebug() << "Test template" << testTemplate->id << "updated in cache.";

    for (auto &overview : m_testTemplateOverviews) {
        if (overview.id == testTemplate->id) {
            if (overview.name != testTemplate->name) {
                overview.name = testTemplate->name;
                //                overviewUpdated = true;
            }
            break;
        }
    }
    emit sig_testTemplatesChanged();
    qDebug() << "Successfully updated test template" << testTemplate->id;
    return true;
}

/**
 * @brief 复制一个现有的测试模板。
 * @param sourceTemplateId 要复制的源测试模板的ID。
 * @return 成功则返回一个指向新创建的TestTemplate对象的智能指针，失败则返回nullptr。
 */
TestTemplatePtr DataManager::duplicateTestTemplate(int sourceTemplateId)
{
    if (sourceTemplateId <= 0) {
        qWarning() << "DataManager::duplicateTestTemplate: Invalid source ID provided.";
        return nullptr;
    }

    qDebug() << "DataManager: Attempting to duplicate test template with ID:" << sourceTemplateId;

    QString dbError;
    TestTemplatePtr newTemplate = m_dbManager->duplicateTestTemplate(sourceTemplateId, &dbError);

    if (!newTemplate) {
        qWarning() << "Database operation failed for duplicating test template" << sourceTemplateId << ". Error:" << dbError;
        return nullptr;
    }

    OverviewItem newItem;
    newItem.id = newTemplate->id;
    newItem.name = newTemplate->name;
    m_testTemplateOverviews.append(newItem);
    m_testTemplateCache.insert(newTemplate->id, newTemplate);

    qDebug() << "Successfully duplicated test template. New ID:" << newTemplate->id << ", Name:" << newTemplate->name;

    emit sig_testTemplatesChanged();
    return newTemplate;
}

/**
 * @brief 创建一个新的硬件模板，并为其所有必要的插槽自动创建带默认值的设备实例。
 * @param name 新模板的名称。
 * @param type 新模板的类型 (RS 或 CS)。
 * @return 如果成功创建，返回一个指向新创建的、数据完整的HardwareTemplate对象的智能指针；否则返回nullptr。
 */
HardwareTemplatePtr DataManager::addHardwareTemplate(const QString &name, HardwareTemplateType type)
{
    //  在内存中构建一个包含所有默认设备的完整对象图
    HardwareTemplatePtr newTemplate = QSharedPointer<HardwareTemplate>::create();
    newTemplate->id = 0; // 明确是新的
    newTemplate->name = name;
    newTemplate->type = type;

    try {
        // -- 创建所有模板都需要的通用设备 --
        newTemplate->d_Generator = QSharedPointer<GeneratorConfig>::create();
        newTemplate->d_Generator->gAttributes.Model = STR_NO_DEVICE;
        newTemplate->d_Generator->gAttributes.type = DeviceType::SignalGenerator;

        newTemplate->d_Amplifier = QSharedPointer<AmplifierConfig>::create();
        newTemplate->d_Amplifier->gAttributes.Model = STR_NO_DEVICE;
        newTemplate->d_Amplifier->gAttributes.type = DeviceType::Amplifier;

        newTemplate->d_FwdPowerMeter = QSharedPointer<PowerMeterConfig>::create();
        newTemplate->d_FwdPowerMeter->gAttributes.Model = STR_NO_DEVICE;
        newTemplate->d_FwdPowerMeter->gAttributes.type = DeviceType::PowerMeter;
        newTemplate->d_RevPowerMeter = QSharedPointer<PowerMeterConfig>::create();
        newTemplate->d_RevPowerMeter->gAttributes.Model = STR_NO_DEVICE;
        newTemplate->d_RevPowerMeter->gAttributes.type = DeviceType::PowerMeter;
        newTemplate->d_MonPowerMeter = QSharedPointer<PowerMeterConfig>::create();
        newTemplate->d_MonPowerMeter->gAttributes.Model = STR_NO_DEVICE;
        newTemplate->d_MonPowerMeter->gAttributes.type = DeviceType::PowerMeter;
        newTemplate->d_MonReceiver = QSharedPointer<ReceiverConfig>::create();
        newTemplate->d_MonReceiver->gAttributes.Model = STR_NO_DEVICE;
        newTemplate->d_MonReceiver->gAttributes.type = DeviceType::Receiver;

        // -- 根据模板类型，创建特有的设备 --
        if (type == HardwareTemplateType::RS) {
            newTemplate->d_RadiatesAntenna = QSharedPointer<AntennaConfig>::create();
            newTemplate->d_RadiatesAntenna->gAttributes.Model = STR_NO_DEVICE;
            newTemplate->d_RadiatesAntenna->gAttributes.type = DeviceType::Antenna;
            newTemplate->d_ReceivesAntenna = QSharedPointer<AntennaConfig>::create();
            newTemplate->d_ReceivesAntenna->gAttributes.Model = STR_NO_DEVICE;
            newTemplate->d_ReceivesAntenna->gAttributes.type = DeviceType::Antenna;
            newTemplate->d_MonFieldProbes = QSharedPointer<FieldProbesConfig>::create();
            newTemplate->d_MonFieldProbes->gAttributes.Model = STR_NO_DEVICE;
            newTemplate->d_MonFieldProbes->gAttributes.type = DeviceType::FieldProbe;
        } else if (type == HardwareTemplateType::CS) {
            newTemplate->d_InjectionTransducer = QSharedPointer<CurrentInjectionProbeConfig>::create();
            newTemplate->d_InjectionTransducer->gAttributes.Model = STR_NO_DEVICE;
            newTemplate->d_InjectionTransducer->gAttributes.type = DeviceType::CurrentInjectionProbe;
            newTemplate->d_MonitoringTransducer = QSharedPointer<CurrentInjectionProbeConfig>::create();
            newTemplate->d_MonitoringTransducer->gAttributes.Model = STR_NO_DEVICE;
            newTemplate->d_MonitoringTransducer->gAttributes.type = DeviceType::CurrentInjectionProbe;
        }

        newTemplate->c_SIG2PA = QSharedPointer<ConnectorConfig>::create();
        newTemplate->c_SIG2PA->gAttributes.Model = STR_NO_DEVICE;
        newTemplate->c_SIG2PA->gAttributes.type = DeviceType::Connector;
        newTemplate->c_SIG2PA->ValueType = 0;  // 恒量
        newTemplate->c_SIG2PA->AttValue = 0.0; // 0dB衰减
        newTemplate->c_FWD2PM = QSharedPointer<ConnectorConfig>::create();
        newTemplate->c_FWD2PM->gAttributes.Model = STR_NO_DEVICE;
        newTemplate->c_FWD2PM->gAttributes.type = DeviceType::Connector;
        newTemplate->c_FWD2PM->ValueType = 0;  // 恒量
        newTemplate->c_FWD2PM->AttValue = 0.0; // 0dB衰减
        newTemplate->c_REV2PM = QSharedPointer<ConnectorConfig>::create();
        newTemplate->c_REV2PM->gAttributes.Model = STR_NO_DEVICE;
        newTemplate->c_REV2PM->gAttributes.type = DeviceType::Connector;
        newTemplate->c_REV2PM->ValueType = 0;  // 恒量
        newTemplate->c_REV2PM->AttValue = 0.0; // 0dB衰减
        newTemplate->c_PA2Transducers = QSharedPointer<ConnectorConfig>::create();
        newTemplate->c_PA2Transducers->gAttributes.Model = STR_NO_DEVICE;
        newTemplate->c_PA2Transducers->gAttributes.type = DeviceType::Connector;
        newTemplate->c_PA2Transducers->ValueType = 0;  // 恒量
        newTemplate->c_PA2Transducers->AttValue = 0.0; // 0dB衰减
        newTemplate->c_Transducers2PM = QSharedPointer<ConnectorConfig>::create();
        newTemplate->c_Transducers2PM->gAttributes.Model = STR_NO_DEVICE;
        newTemplate->c_Transducers2PM->gAttributes.type = DeviceType::Connector;
        newTemplate->c_Transducers2PM->ValueType = 0;  // 恒量
        newTemplate->c_Transducers2PM->AttValue = 0.0; // 0dB衰减

    } catch (const std::bad_alloc &e) {
        qWarning() << "Memory allocation failed while creating default devices for new template:" << e.what();
        return nullptr;
    }

    if (!m_dbManager->insertHardwareTemplate(*newTemplate)) {
        qWarning() << "Database failed to insert the new full hardware template.";
        return nullptr;
    }

    //  更新内存状态 (缓存和概览列表)
    OverviewItem item;
    item.id = newTemplate->id;
    item.name = newTemplate->name;
    m_hardwareTemplateOverviews.append(item);
    m_hardwareTemplateCache.insert(newTemplate->id, newTemplate);

    // 将所有新创建的私有设备也加入到全局设备缓存中
    if (newTemplate->d_Generator)
        m_deviceCache.insert(newTemplate->d_Generator->gAttributes.ID, newTemplate->d_Generator);
    if (newTemplate->d_Amplifier)
        m_deviceCache.insert(newTemplate->d_Amplifier->gAttributes.ID, newTemplate->d_Amplifier);
    if (newTemplate->d_FwdPowerMeter)
        m_deviceCache.insert(newTemplate->d_FwdPowerMeter->gAttributes.ID, newTemplate->d_FwdPowerMeter);
    if (newTemplate->d_RevPowerMeter)
        m_deviceCache.insert(newTemplate->d_RevPowerMeter->gAttributes.ID, newTemplate->d_RevPowerMeter);
    if (newTemplate->d_MonPowerMeter)
        m_deviceCache.insert(newTemplate->d_MonPowerMeter->gAttributes.ID, newTemplate->d_MonPowerMeter);
    if (newTemplate->d_MonReceiver)
        m_deviceCache.insert(newTemplate->d_MonReceiver->gAttributes.ID, newTemplate->d_MonReceiver);
    if (type == HardwareTemplateType::RS) {
        if (newTemplate->d_RadiatesAntenna)
            m_deviceCache.insert(newTemplate->d_RadiatesAntenna->gAttributes.ID, newTemplate->d_RadiatesAntenna);
        if (newTemplate->d_ReceivesAntenna)
            m_deviceCache.insert(newTemplate->d_ReceivesAntenna->gAttributes.ID, newTemplate->d_ReceivesAntenna);
        if (newTemplate->d_MonFieldProbes)
            m_deviceCache.insert(newTemplate->d_MonFieldProbes->gAttributes.ID, newTemplate->d_MonFieldProbes);
    } else {
        if (newTemplate->d_InjectionTransducer)
            m_deviceCache.insert(newTemplate->d_InjectionTransducer->gAttributes.ID, newTemplate->d_InjectionTransducer);
        if (newTemplate->d_MonitoringTransducer)
            m_deviceCache.insert(newTemplate->d_MonitoringTransducer->gAttributes.ID, newTemplate->d_MonitoringTransducer);
    }
    //    if (newTemplate->d_SpectrumAnalyzer)
    //        m_deviceCache.insert(newTemplate->d_SpectrumAnalyzer->gAttributes.ID, newTemplate->d_SpectrumAnalyzer);
    if (newTemplate->c_SIG2PA)
        m_deviceCache.insert(newTemplate->c_SIG2PA->gAttributes.ID, newTemplate->c_SIG2PA);
    if (newTemplate->c_FWD2PM)
        m_deviceCache.insert(newTemplate->c_FWD2PM->gAttributes.ID, newTemplate->c_FWD2PM);
    if (newTemplate->c_REV2PM)
        m_deviceCache.insert(newTemplate->c_REV2PM->gAttributes.ID, newTemplate->c_REV2PM);
    if (newTemplate->c_PA2Transducers)
        m_deviceCache.insert(newTemplate->c_PA2Transducers->gAttributes.ID, newTemplate->c_PA2Transducers);
    if (newTemplate->c_Transducers2PM)
        m_deviceCache.insert(newTemplate->c_Transducers2PM->gAttributes.ID, newTemplate->c_Transducers2PM);

    qDebug() << "Successfully created new hardware template with default devices. ID:" << newTemplate->id;
    emit sig_hardwareTemplatesChanged();
    return newTemplate;
}

/**
 * @brief 删除一个硬件模板及其所有关联。
 *
 * 这个函数会执行以下操作：
 *调用DatabaseManager从数据库中删除指定的硬件模板记录。
 * 2. 从内存中的硬件模板概览列表中移除对应的项。
 * 3. 从硬件模板缓存中移除该模板（如果存在）。
 * 4. 如果被删除的模板是当前选中的，则清空当前选择状态。
 * 5. 发射信号通知UI进行刷新。
 *
 * @param id 要删除的硬件模板的ID。
 * @return 如果数据库删除成功，返回true；否则返回false。
 */
bool DataManager::removeHardwareTemplate(int id)
{
    if (id <= 0) {
        qWarning() << "DataManager::removeHardwareTemplate: Invalid ID (" << id << ") provided.";
        return false;
    }

    qDebug() << "Attempting to remove hardware template with ID:" << id;

    //  调用数据库层执行删除操作
    // 假设它在失败时会打印详细的SQL错误。
    if (!m_dbManager->deleteHardwareTemplate(id)) {
        qWarning() << "Database operation failed for deleting hardware template" << id;
        return false;
    }

    //  从内存中的概览列表中移除
    qDebug() << "Searching for hardware template" << id << "in overview list to remove.";

    // 使用 std::remove_if 将要删除的元素移动到列表末尾
    auto newEnd = std::remove_if(m_hardwareTemplateOverviews.begin(),
                                 m_hardwareTemplateOverviews.end(),
                                 [id](const OverviewItem &item) {
                                     return item.id == id;
                                 });

    bool removedFromOverviews = (newEnd != m_hardwareTemplateOverviews.end());

    // 使用 QList::erase 删除从 newEnd 到结尾的所有元素
    if (removedFromOverviews) {
        m_hardwareTemplateOverviews.erase(newEnd, m_hardwareTemplateOverviews.end());
        qDebug() << "Removed hardware template" << id << "from overview list.";
    }

    //  从缓存中移除
    if (m_hardwareTemplateCache.contains(id)) {
        m_hardwareTemplateCache.remove(id);
        qDebug() << "Removed hardware template" << id << "from cache.";
    }

    //  检查并清空当前选中状态
    bool selectionCleared = false;
    if (m_selectedHardwareTemplate && m_selectedHardwareTemplate->id == id) {
        m_selectedHardwareTemplate.clear(); // 清空智能指针
        selectionCleared = true;
        qDebug() << "Cleared the current selection as it was the deleted template.";
    }

    qDebug() << "Successfully removed hardware template" << id;
    emit sig_hardwareTemplatesChanged();
    return true;
}

/**
 * @brief 更新一个已有的硬件模板。
 *        这个函数接收一个包含了最终状态的HardwareTemplate对象，并将其同步到数据库和内存缓存。
 * @param hwTemplate 指向要更新的硬件模板数据的智能指针。其ID必须有效。
 * @return 如果成功更新，返回true。
 */
bool DataManager::updateHardwareTemplate(HardwareTemplatePtr hwTemplate)
{
    if (!hwTemplate || hwTemplate->id <= 0) {
        qWarning() << "DataManager::updateHardwareTemplate: Invalid or non-existent template provided for update.";
        return false;
    }

    qDebug() << "Attempting to update hardware template with ID:" << hwTemplate->id;

    // 确保用户修改后的新名称，不会与另一个已存在的模板重名。
    const auto &overviews = getHardwareTemplateOverviews();
    for (const auto &item : overviews) {
        // 如果找到另一个ID不同但名称相同的模板
        if (item.id != hwTemplate->id && item.name.compare(hwTemplate->name, Qt::CaseInsensitive) == 0) {
            qWarning() << "DataManager::updateHardwareTemplate: Failed. Another template with the name '" << hwTemplate->name << "' already exists.";
            return false;
        }
    }

    if (!m_dbManager->updateHardwareTemplate(*hwTemplate)) { // 解引用传递
        qWarning() << "Database operation failed for updating hardware template" << hwTemplate->id;
        return false;
    }

    // 用包含了最新数据的智能指针，替换掉缓存中旧的那个
    m_hardwareTemplateCache.insert(hwTemplate->id, hwTemplate);
    qDebug() << "Hardware template" << hwTemplate->id << "updated in cache.";

    bool overviewUpdated = false;
    for (auto &overview : m_hardwareTemplateOverviews) {
        if (overview.id == hwTemplate->id) {
            if (overview.name != hwTemplate->name) {
                overview.name = hwTemplate->name;
                overviewUpdated = true;
            }
            break;
        }
    }

    qDebug() << "Successfully updated hardware template" << hwTemplate->id;
    emit sig_hardwareTemplatesChanged();
    return true;
}

static DeviceType driverStringToDeviceType(const QString &driverStr)
{
    if (driverStr == STR_DEVICE_TYPE_SignalGenerators) {
        return DeviceType::SignalGenerator;
    } else if (driverStr == STR_DEVICE_TYPE_PowerAmplifiers) {
        return DeviceType::Amplifier;
    } else if (driverStr == STR_DEVICE_TYPE_FieldProbes) {
        return DeviceType::FieldProbe;
    } else if (driverStr == STR_DEVICE_TYPE_PowerMeters) {
        return DeviceType::PowerMeter;
    } else if (driverStr == STR_DEVICE_TYPE_SwitchUnits) {
        return DeviceType::SwitchUnits;
    } else if (driverStr == STR_DEVICE_TYPE_Receivers) {
        return DeviceType::Receiver;
    } else if (driverStr == STR_DEVICE_TYPE_SpectrumAnalyzers) {
        return DeviceType::SpectrumAnalyzer;
    }
    // 如果没有匹配的类型，返回 Undefined
    return DeviceType::Undefined;
}

bool DataManager::loadAndCacheDeviceModel()
{
    QString path = QCoreApplication::applicationDirPath() + "/drivers/";

    //获取驱动文件夹列表
    QDirIterator it(path, QDir::Dirs | QDir::NoSymLinks | QDir::NoDotAndDotDot, QDirIterator::Subdirectories);
    QStringList folderList;
    while (it.hasNext()) {
        it.next();
        QString folderName = it.fileName();
        folderList.append(folderName);
    }

    m_deviceModelCache.clear();
    m_modelToDeviceTypeCache.clear();
    m_modelToLibraryPathCache.clear();

    foreach (QString driver, folderList) {
        QStringList str_camList;

        QString driverPath = path + driver + "/";
        QString fileExtension = "*.dll";
        QDirIterator it(driverPath, QStringList() << fileExtension, QDir::Files | QDir::NoSymLinks, QDirIterator::Subdirectories);
        QString fileName;
        while (it.hasNext()) {
            it.next();
            fileName = it.fileName();
            // 调用固定接口 获取支持的设备型号列表
            IDevice *device = DeviceInstanceManager::createInstance<IDevice *>(driverPath + fileName);
            if (!device) {
                qCritical() << "device is null! fileName: " << driverPath + fileName;
                break;
            }
            QString iid = device->iid();
            QStringList result = device->type();
            if ((iid != "rflight.TE.Qt.Device") || (result[0] != driver)) {
                qCritical() << "不能识别的设备驱动：" << fileName;
                continue;
            }
            // 显示型号
            result.removeFirst();
            str_camList += result;

            // 把型号 -> 库路径 记录到当前目录的临时 map
            for (const QString &modelName : result) {
                if (modelName.trimmed().isEmpty())
                    continue;
                m_modelToLibraryPathCache.insert(modelName, fileName);
                m_modelToDeviceTypeCache.insert(modelName, driverStringToDeviceType(driver));
            }

            DeviceInstanceManager::destroyInstance(device);
        }

        if (driver == STR_DEVICE_TYPE_SignalGenerators)
            m_deviceModelCache.insert(DeviceRole::SignalGenerator, str_camList);
        else if (driver == STR_DEVICE_TYPE_PowerAmplifiers)
            m_deviceModelCache.insert(DeviceRole::Amplifier, str_camList);
        else if (driver == STR_DEVICE_TYPE_Receivers)
            m_deviceModelCache.insert(DeviceRole::Receiver, str_camList);
        else if (driver == STR_DEVICE_TYPE_SpectrumAnalyzers)
            m_deviceModelCache.insert(DeviceRole::SpectrumAnalyzer, str_camList);
        else if (driver == STR_DEVICE_TYPE_FieldProbes) {
            str_camList.append(STR_DEVICE_TYPE_GeneralAntenna);
            m_deviceModelCache.insert(DeviceRole::FieldProbe, str_camList);
            m_deviceModelCache.insert(DeviceRole::AntennaRadiates, str_camList);
            m_deviceModelCache.insert(DeviceRole::AntennaReceives, str_camList);
            //            m_deviceModelCache.insert(DeviceRole::AntennaRadiates, QStringList(STR_DEVICE_TYPE_GeneralAntenna));
            //            m_deviceModelCache.insert(DeviceRole::AntennaReceives, QStringList(STR_DEVICE_TYPE_GeneralAntenna));
        } else if (driver == STR_DEVICE_TYPE_PowerMeters) {
            m_deviceModelCache.insert(DeviceRole::PowerMeterForward, str_camList);
            m_deviceModelCache.insert(DeviceRole::PowerMeterReverse, str_camList);
            m_deviceModelCache.insert(DeviceRole::PowerMeterMonitor, str_camList);
        } else if (driver == STR_DEVICE_TYPE_SwitchUnits) {
            m_deviceModelCache.insert(DeviceRole::Connector_SIG2PA, str_camList);
            m_deviceModelCache.insert(DeviceRole::Connector_FWD2PM, str_camList);
            m_deviceModelCache.insert(DeviceRole::Connector_REV2PM, str_camList);
            m_deviceModelCache.insert(DeviceRole::Connector_PA2Transducers, str_camList);
            m_deviceModelCache.insert(DeviceRole::Connector_Transducers2PM, str_camList);
        }
    }
    m_deviceModelCache.insert(DeviceRole::CurrentInjectionProbeInput, QStringList(STR_DEVICE_TYPE_GeneralCurrentInjectionProbe));
    m_deviceModelCache.insert(DeviceRole::CurrentInjectionProbeMonitor, QStringList(STR_DEVICE_TYPE_GeneralCurrentInjectionProbe));
    m_modelToDeviceTypeCache.insert(STR_DEVICE_TYPE_GeneralAntenna, DeviceType::Antenna);
    m_modelToDeviceTypeCache.insert(STR_DEVICE_TYPE_GeneralCurrentInjectionProbe, DeviceType::CurrentInjectionProbe);
    return true;
}

QStringList DataManager::getDeviceModelList(const DeviceRole role)
{
    return m_deviceModelCache.value(role);
}

QStringList DataManager::getDeviceModelList(const DeviceType Type)
{
    QStringList list;
    for (auto it = m_modelToDeviceTypeCache.constBegin(); it != m_modelToDeviceTypeCache.constEnd(); ++it) {
        if (it.value() == Type)
            list.append(it.key());
    }
    return list;
}

DeviceRole DataManager::getDeiceRoleForModel(const QString &model) const
{
    // 遍历缓存 m_deviceModelCache
    for (auto it = m_deviceModelCache.constBegin(); it != m_deviceModelCache.constEnd(); ++it) {
        const DeviceRole &role = it.key();
        const QStringList &models = it.value();

        // 检查当前角色对应的型号列表中是否包含目标型号
        if (models.contains(model, Qt::CaseSensitive)) { // Qt::CaseSensitive 保持与添加时一致
            return role;
        }
    }

    // 检查特殊型号
    // 如果请求的是通用天线型号，返回一个相关的天线角色（例如 AntennaRadiates）
    if (model == STR_DEVICE_TYPE_GeneralAntenna) {
        if (m_deviceModelCache.value(DeviceRole::AntennaRadiates).contains(STR_DEVICE_TYPE_GeneralAntenna)) {
            return DeviceRole::AntennaRadiates;
        }
        // Fallback: 检查其他相关角色
        if (m_deviceModelCache.value(DeviceRole::AntennaReceives).contains(STR_DEVICE_TYPE_GeneralAntenna)) {
            return DeviceRole::AntennaReceives;
        }
    }
    // 如果请求的是通用电流探头型号
    else if (model == STR_DEVICE_TYPE_GeneralCurrentInjectionProbe) {
        if (m_deviceModelCache.value(DeviceRole::CurrentInjectionProbeInput).contains(STR_DEVICE_TYPE_GeneralCurrentInjectionProbe)) {
            return DeviceRole::CurrentInjectionProbeInput;
        }
        if (m_deviceModelCache.value(DeviceRole::CurrentInjectionProbeMonitor).contains(STR_DEVICE_TYPE_GeneralCurrentInjectionProbe)) {
            return DeviceRole::CurrentInjectionProbeMonitor;
        }
    }

    return DeviceRole::Undefined;
}

DeviceType DataManager::getDeiceTypeForModel(const QString &model) const
{
    auto it = m_modelToDeviceTypeCache.find(model);
    if (it != m_modelToDeviceTypeCache.constEnd()) {
        return it.value();
    }

    return DeviceType::Undefined;
}

QString DataManager::libraryPathForModel(const QString &model) const
{
    return m_modelToLibraryPathCache.value(model);
}

bool DataManager::overVivewNameExists(const QList<OverviewItem> &list, const QString &name) const
{
    // 直接在内存中的概览列表上检查，效率最高
    for (const auto &overview : list) {
        if (overview.name.compare(name, Qt::CaseInsensitive) == 0) {
            return true;
        }
    }
    return false;
}

int DataManager::findIDByOverViewName(const QList<OverviewItem> &list, const ParamTableKind type, const QString &name) const
{
    foreach (auto item, list) {
        if (item.type == type)
            if (item.name == name)
                return item.id;
    }
    return -1;
}

QString DataManager::findNameByOverViewID(const QList<OverviewItem> &list, const ParamTableKind type, int id) const
{
    foreach (auto item, list) {
        if (item.type == type)
            if (item.id == id)
                return item.name;
    }
    return "";
}

QString DataManager::getParamTableEnumString(const ParamTableKind type)
{
    switch (type) {
    case ParamTableKind::Attenuation:
        return tr("AttTables");
    case ParamTableKind::Transducer:
        return tr("TransducerTables");
    case ParamTableKind::LimitLine:
        return tr("LimitLines");
    case ParamTableKind::Frequency:
        return tr("FreqTables");
    case ParamTableKind::Cal:
        return tr("CalibrationTables");
    default:
        return "";
    }
}

/**
 * @brief 复制一个现有的硬件模板。
 *        此方法会处理数据库复制、内存缓存更新和UI通知。
 * @param sourceTemplateId 要复制的源硬件模板的ID。
 * @return 成功则返回一个指向新创建的HardwareTemplate对象的智能指针，失败则返回nullptr。
 */
HardwareTemplatePtr DataManager::duplicateHardwareTemplate(int sourceTemplateId)
{
    if (sourceTemplateId <= 0) {
        qWarning() << "DataManager::duplicateHardwareTemplate: Invalid source ID provided.";
        return nullptr;
    }

    qDebug() << "DataManager: Attempting to duplicate hardware template with ID:" << sourceTemplateId;

    QString dbError;
    HardwareTemplatePtr newTemplate = m_dbManager->duplicateHardwareTemplate(sourceTemplateId, &dbError);

    if (!newTemplate) {
        qWarning() << "Database operation failed for duplicating hardware template" << sourceTemplateId << ". Error:" << dbError;
        return nullptr;
    }

    OverviewItem newItem;
    newItem.id = newTemplate->id;
    newItem.name = newTemplate->name;
    m_hardwareTemplateOverviews.append(newItem);
    m_hardwareTemplateCache.insert(newTemplate->id, newTemplate);

    qDebug() << "Successfully duplicated template. New ID:" << newTemplate->id << ", Name:" << newTemplate->name;

    emit sig_hardwareTemplatesChanged();
    return newTemplate;
}

const HardwareTemplatePtr DataManager::loadAndCacheHardwareTemplate(int id)
{
    if (!m_hardwareTemplateCache.contains(id)) {
        HardwareTemplatePtr hw = m_dbManager->loadFullHardwareTemplate(id);
        if (hw) {
            m_hardwareTemplateCache.insert(id, hw);
        }
    }
    return m_hardwareTemplateCache.value(id, nullptr);
}

const TestTemplatePtr DataManager::loadAndCacheTestTemplate(int id)
{
    if (!m_testTemplateCache.contains(id)) {
        TestTemplatePtr hw = m_dbManager->loadFullTestTemplate(id);
        if (hw) {
            m_testTemplateCache.insert(id, hw);
        }
    }
    return m_testTemplateCache.value(id, nullptr);
}

bool DataManager::hardwareTemplateNameExists(const QString &name) const
{
    // 直接在内存中的概览列表上检查，效率最高
    for (const auto &overview : m_hardwareTemplateOverviews) {
        if (overview.name.compare(name, Qt::CaseInsensitive) == 0) {
            return true;
        }
    }
    return false;
}

bool DataManager::addParameterTable(OverviewItem &item)
{
    if (item.name.trimmed().isEmpty() || item.type == ParamTableKind::Default)
        return false;
    int newId = m_dbManager->insertNewParameterTableMeta(item.name, item.type);

    if (newId > 0) {
        item.id = newId;
        // 更新内存中的概览列表
        m_parameterTableOverviews.append(item);
        emit sig_parameterTablesChanged();
        return true;
    }

    return false;
}

bool DataManager::removeParameterTable(int id, const ParamTableKind type)
{
    if (id <= 0)
        return false;
    bool ok = m_dbManager->deleteParameterTable(id, type);
    if (ok) {
        // 刷新缓存，供 TreeModel::refresh 使用
        m_parameterTableOverviews = m_dbManager->loadParameterTableOverviews();
        emit sig_parameterTablesChanged();
    }
    return ok;
}

// bool DataManager::parameterTableNameExists(const QString &name, const ParamTableKind kind) const
// {
//     for (const auto &overview : m_parameterTableOverviews) {
//         if (overview.name.compare(name, Qt::CaseInsensitive) == 0) {
//             return true;
//         }
//     }
//     return false;
// }
/**
 * @brief 复制一个现有的参数表。
 * @param sourceTableId 要复制的源表的ID。
 * @param kind 源表的类型。
 * @return 成功则返回包含新表信息的OverviewItem，失败则返回一个无效的Item (id <= 0)。
 */
OverviewItem DataManager::duplicateParameterTable(int sourceTableId, ParamTableKind kind)
{
    OverviewItem invalidItem;
    invalidItem.id = -1;

    if (sourceTableId <= 0 || kind == ParamTableKind::Default || kind == ParamTableKind::Cal) {
        qWarning() << "DataManager::duplicateParameterTable: Invalid parameters provided.";
        return invalidItem;
    }

    // 生成一个唯一的新名称
    QString sourceName;
    for (const auto &overview : m_parameterTableOverviews) {
        if (overview.id == sourceTableId && overview.type == kind) {
            sourceName = overview.name;
            break;
        }
    }
    if (sourceName.isEmpty()) {
        qWarning() << "Could not find source table name for ID" << sourceTableId;
        return invalidItem;
    }

    QString baseName = sourceName;
    QRegExp copyPattern(" - Copy( \\d+)?$");
    baseName.remove(copyPattern);

    QString newName = baseName + " - Copy";
    int counter = 2;
    while (parameterTableNameExists(newName, kind)) { // parameterTableNameExists需要检查同类型下是否重名
        newName = QString("%1 - Copy %2").arg(baseName).arg(counter++);
    }

    QString dbError;
    int newId = m_dbManager->duplicateParameterTable(sourceTableId, kind, newName, &dbError);

    if (newId <= 0) {
        qWarning() << "Database operation failed for duplicating parameter table" << sourceTableId << ". Error:" << dbError;
        return invalidItem;
    }

    // 更新内存状态
    OverviewItem newItem;
    newItem.id = newId;
    newItem.name = newName;
    newItem.type = kind;
    m_parameterTableOverviews.append(newItem);

    qDebug() << "Successfully duplicated parameter table. New ID:" << newItem.id << ", Name:" << newItem.name;
    emit sig_parameterTablesChanged();
    return newItem;
}

bool DataManager::parameterTableNameExists(const QString &name, const ParamTableKind kind) const
{
    for (const auto &overview : m_parameterTableOverviews) {
        // 增加类型匹配
        if (overview.type == kind && overview.name.compare(name, Qt::CaseInsensitive) == 0) {
            return true;
        }
    }
    return false;
}

bool DataManager::saveAttTable(int id, const QString &name, const AttTableList &t)
{
    if (m_dbManager && m_dbManager->saveAttTable(id, name, t)) {
        m_parameterTableOverviews = m_dbManager->loadParameterTableOverviews();
        emit sig_parameterTablesChanged();
        return true;
    }
    return false;
}

bool DataManager::saveTransducerTable(int tableId, const QString &name, const TransducerTableList &t)
{
    if (m_dbManager && m_dbManager->saveTransducerTable(tableId, name, t)) {
        m_parameterTableOverviews = m_dbManager->loadParameterTableOverviews();
        emit sig_parameterTablesChanged();
        return true;
    }
    return false;
}

bool DataManager::saveLimitLineTable(int tableId, const QString &name, const LimitLineList &t)
{
    if (m_dbManager && m_dbManager->saveLimitLineTable(tableId, name, t)) {
        m_parameterTableOverviews = m_dbManager->loadParameterTableOverviews();
        emit sig_parameterTablesChanged();
        return true;
    }
    return false;
}

bool DataManager::saveFreqTable(int tableId, const QString &name, const QList<FreqTableConfig> &rows)
{
    if (m_dbManager && m_dbManager->saveFreqTable(tableId, name, rows)) {
        m_parameterTableOverviews = m_dbManager->loadParameterTableOverviews();
        emit sig_parameterTablesChanged();
        return true;
    }
    return false;
}

bool DataManager::saveCalibrationTable(int tableId, const QString &name, const QList<CalTableConfig> &rows)
{
    if (m_dbManager && m_dbManager->saveCalibrationTable(tableId, name, rows)) {
        m_parameterTableOverviews = m_dbManager->loadParameterTableOverviews();
        emit sig_parameterTablesChanged();
        return true;
    }
    return false;
}
